<?php
/**
 * TinyCatPHP 极简、快速、创新、易用、高性能的PHP应用开发框架
 * User: CnTaiGe <hst042@163.com>
 * Date: 2017/10/29
 */

namespace TinyCatPHP\libs;

use TinyCatPHP\exception\SysException;
use TinyCatPHP\libs\config\Config;
use TinyCatPHP\libs\handler\Interceptor;
use TinyCatPHP\libs\handler\Request;
use TinyCatPHP\libs\handler\Response;
use TinyCatPHP\libs\utils\Log;
use TinyCatPHP\libs\utils\Running;

class App
{

    /**
     * 开始执行框架
     */
    public static function run()
    {
        $app = new self();
        self::init();
        Interceptor::instance()->initApp();
        $app->handlerRoute(Request::requestUrl());
    }

    /**
     * 初始化应用
     */
    protected static function init()
    {
        $com = APP_PATH . '/common/';
        if (is_dir($com)) {
            $a = scandir($com);
            array_map(function ($r) use ($com) {
                if ($r === '.' || $r === '..') return;
                $pathinfo = pathinfo($r);
                if ($pathinfo['extension'] === 'php')
                    include $com . $r;
            }, $a);
        }
    }

    private function __construct()
    {
        $this->autoLoadCls();
        SysException::register();
        //初始化配置
        Config::init();
        $this->loadFile();
        Log::record('info', '---------------------------------');
        Log::record('info', '初始化应用');
        Running::tagTime('app_run');
        Request::record();
    }

    public function loadFile()
    {
        include_once TINY_CAT_SYS_ROOT . '/common/common.php';
    }

    /**
     * 路由操作
     * @param $requestUri
     * @throws SysException
     */
    protected function handlerRoute($requestUri)
    {
        $routers = Routes::instance()->getRoutes();
        Running::tagTime('service_logic');
        Running::tagMemory('service_logic');
        Interceptor::instance()->createAction();
        $requestUri = urldecode($requestUri);
        if (isset($routers[$requestUri])) {
            //定义路由响应
            Response::routers($routers, $requestUri);
        } else {
            Response::moduleAction($requestUri);
        }
        Interceptor::instance()->endAction();
        if (function_exists('fastcgi_finish_request'))
            fastcgi_finish_request();
    }


    /**
     * 注册自动加载类
     */
    protected function autoLoadCls()
    {
        spl_autoload_register(function ($file) {
            //注册自动加载类
            $pathFile = str_replace('\\', '/', $file);
            $inFile = APP_PATH . '/' . $pathFile . '.php';
            if (!file_exists($inFile))
                $inFile = APP_ROOT_PATH . '/' . $pathFile . '.php';
            if (!file_exists($inFile)) {
                throw new SysException("找不到类 {$file} ");
            }
            include_once $inFile;
        });
    }
}